package front.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import reggie.common.BaseContext;
import reggie.common.R;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: LoginCheckFilter <br/>
 * Description: <br/>
 * date: 2022/11/29 16:19<br/>
 *
 * @author Xingyingsheng<br />
 * @since JDK 11
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String requestURI = httpServletRequest.getRequestURI();
        log.info("拦截到{}", requestURI);

        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        boolean check = check(urls, requestURI);

        if (check) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
//      判断登录状态，如果登录放行，网页端
        if (httpServletRequest.getSession().getAttribute("employee") != null) {

            long id = Thread.currentThread().getId();
            log.info("过滤器，线程id为：{}",id);
            //存入线程threadLocal中，方便取出
            Long empId = (Long) httpServletRequest.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        //      判断登录状态，如果登录放行，移动端
        if (httpServletRequest.getSession().getAttribute("user") != null) {

            long id = Thread.currentThread().getId();
            log.info("过滤器，线程id为：{}",id);
            //存入线程threadLocal中，方便取出
            Long userId = (Long) httpServletRequest.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }

        httpServletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
